package model

import (
	"database/sql"
	"fmt"
	"forum/app/config"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

var DB *sql.DB

func InitDB() {
	var err error
	fmt.Printf("%v %v %v %v %v", config.DatabaseConfig.Username, config.DatabaseConfig.Password, config.DatabaseConfig.Host, config.DatabaseConfig.Port, config.DatabaseConfig.Database)
	DB, err = sql.Open("mysql", fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8&parseTime=True&loc=Local",
		config.DatabaseConfig.Username,
		config.DatabaseConfig.Password,
		config.DatabaseConfig.Host,
		config.DatabaseConfig.Port,
		config.DatabaseConfig.Database,
	))

	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}

	// 设置连接池
	DB.SetMaxOpenConns(100)
	DB.SetMaxIdleConns(10)

	// 测试连接
	if err = DB.Ping(); err != nil {
		log.Fatal("数据库Ping失败:", err)
	}

	fmt.Println("数据库连接成功")
}
